package web4;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.*;
import java.nio.file.*;

@WebServlet("/ProductUploadServlet")
public class ProductUploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取上传的文件
        Part filePart = request.getPart("image");
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
        String uploadPath = getServletContext().getRealPath("/uploads/") + fileName;

        // 保存文件到服务器
        filePart.write(uploadPath);

        // 获取其他表单数据
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        double price = Double.parseDouble(request.getParameter("price"));

        // 创建Product对象并设置属性
        Product product = new Product();
        product.setId(id);
        product.setName(name);
        product.setPrice(price);
        product.setImagePath("/uploads/" + fileName);

        // 将Product对象保存到request作用域
        request.setAttribute("product", product);

        // 转发到displayProduct.jsp页面
        RequestDispatcher dispatcher = request.getRequestDispatcher("displayProduct.jsp");
        dispatcher.forward(request, response);
    }
}
